<template>
    <Modal :value="show" :width="720" @on-visible-change="setVisibility" title="导出工单">
        <div style="padding:20px 30px">
            <Row :gutter="30" class="margin-bottom-20" type="flex">
                <i-col class="c-ticket__row" span="12">
                    <span class="c-ticket__label c-ticket__label--width">工单类型</span>
                    <div class="c-ticket__item">
                        <Select class="width-100p" v-model="param.type">
                            <Option :value="1">预约安装</Option>
                            <Option :value="2">售后维修</Option>
                            <Option :value="3">拆卸工单</Option>
                            <Option :value="4">重装工单</Option>
                        </Select>
                    </div>
                </i-col>
                <i-col class="c-ticket__row" span="12" v-if="param.type === 1">
                    <span class="c-ticket__label c-ticket__label--width">设备类型</span>
                    <div class="c-ticket__item">
                        <device-type-selector v-model="param.device_type"></device-type-selector>
                    </div>
                </i-col>
            </Row>

            <Row :gutter="30" class="margin-bottom-20" type="flex">
                <i-col class="c-ticket__row" span="12">
                    <span class="c-ticket__label c-ticket__label--width">商户名称</span>
                    <div class="c-ticket__item">
                        <Select
                            :loading="loadingClients"
                            :remote-method="handleSearchClients"
                            clearable
                            filterable
                            placeholder="请输入商户手机号/名称搜索"
                            remote
                            v-model="param.client"
                        >
                            <Option
                                :key="index"
                                :value="option.id"
                                v-for="(option, index) in clients"
                            >{{option.name + ' ' + option.user.telephone}}</Option>
                        </Select>
                    </div>
                </i-col>
                <i-col class="c-ticket__row" span="12">
                    <span class="c-ticket__label c-ticket__label--width">所在城市</span>
                    <div class="c-ticket__item">
                        <city-code-selector v-model="param.city"></city-code-selector>
                    </div>
                </i-col>
            </Row>

            <Row :gutter="30" class="margin-bottom-20" type="flex">
                <i-col class="c-ticket__row" span="12">
                    <span class="c-ticket__label c-ticket__label--width">工单状态</span>
                    <div class="c-ticket__item">
                        <Select class="width-100p" clearable multiple v-model="param.state">
                            <Option :key="key" :value="key" v-for="(value, key) in states">{{value}}</Option>
                        </Select>
                    </div>
                </i-col>
                <i-col class="c-ticket__row" span="12">
                    <span class="c-ticket__label c-ticket__label--width">工单标签</span>
                    <div class="c-ticket__item">
                        <Select class="width-100p" clearable multiple v-model="param.tags">
                            <Option :value="1">延期工单</Option>
                            <Option :value="2">改约工单</Option>
                            <Option :value="3">签到工单</Option>
                        </Select>
                    </div>
                </i-col>
            </Row>

            <Row :gutter="30" class="margin-bottom-20" type="flex">
                <i-col class="c-ticket__row" span="24">
                    <span class="c-ticket__label c-ticket__label--width">创建时间</span>
                    <div class="c-ticket__item">
                        <DatePicker class="width-100p" format="yyyy-MM-dd" type="datetimerange" v-model="param.time"></DatePicker>
                    </div>
                </i-col>
            </Row>

            <Row :gutter="30" class="margin-bottom-20" type="flex">
                <i-col class="c-ticket__row" span="24">
                    <span class="c-ticket__label c-ticket__label--width">预约上门时间</span>
                    <div class="c-ticket__item">
                        <DatePicker class="width-100p" format="yyyy-MM-dd" type="datetimerange" v-model="param.appointment_time"></DatePicker>
                    </div>
                </i-col>
            </Row>
        </div>

        <Row slot="footer">
            <Button @click="setVisibility(false)" type="text">取消</Button>
            <Button @click="handleExport" type="primary">确定</Button>
        </Row>
    </Modal>
</template>

<script>
import debounce from 'lodash/debounce'
import cityCodeSelector from '@/components/city-code-selector'
import deviceTypeSelector from './device-type-selector'
import { TicketInstallState, TicketRepairState } from '@/libs/const'
import { http, api } from '@/libs/http'
import util from '@/libs/util'
import { dayjs, startOfDay, endOfDay } from '@/libs/date'

export default {
  name: 'ticket-exporter',
  components: {
    deviceTypeSelector,
    cityCodeSelector
  },
  props: {
    show: Boolean
  },
  data () {
    return {
      loadingClients: false,
      clients: [],
      cities: [],
      param: {
        appointment_time: [],
        device_type: [],
        client_id: '',
        state: [],
        time: [],
        city: '',
        type: 1,
        tags: []
      }
    }
  },
  computed: {
    states () {
      if (!this.param.type) return []
      return this.param.type === 1 ? TicketInstallState : TicketRepairState
    }
  },
  methods: {
    setVisibility (val) {
      this.$emit('update:show', val)
    },
    isBetweenThreeMonth (start, end) {
      if (!start || !end) return false
      return (
        dayjs(start)
          .add(3, 'M')
          .valueOf() -
                    dayjs(end).valueOf() >=
                0
      )
    },
    illegalTicketTime (params) {
      const { start_time, end_time, appointment_start_time, appointment_end_time } = params
      const notHasCreateTime = !start_time && !end_time
      const notHasAppointmentTime = !appointment_start_time && !appointment_end_time
      if (notHasCreateTime && notHasAppointmentTime) {
        return '最多导出三个月的工单，请选择预约上门时间范围或创建时间范围'
      }
      return this.isBetweenThreeMonth(start_time, end_time) || this.isBetweenThreeMonth(appointment_start_time, appointment_end_time)
        ? false
        : '最多导出三个月的工单'
    },
    generateData () {
      const { type, time, appointment_time, tags, state, device_type, ...rest } = this.param
      const data = { ...rest }
      if (appointment_time.length > 0) {
        data.appointment_start_time = startOfDay(appointment_time[0])
        data.appointment_end_time = endOfDay(appointment_time[1])
      }
      if (tags.length) data.tags = JSON.stringify(tags)
      if (state.length) data.state = JSON.stringify(state)
      if (type === 1 && device_type.length) data.device_type = JSON.stringify(device_type)
      if (time.length > 0) {
        data.start_time = startOfDay(time[0])
        data.end_time = endOfDay(time[1])
      }
      return util.cleanObj(data)
    },
    handleExport () {
      const params = this.generateData()
      const validResult = this.illegalTicketTime(params)
      if (validResult) {
        this.$Message.error({
          content: validResult,
          duration: 6
        })
      } else {
        http.exportTable(this, api.ticket_export, [this.param.type], params)
      }
    },
    checkKeywordInclude (keyword) {
      return this.clients.length && this.clients.find(client => keyword.includes(client.user.telephone))
    },
    handleSearchClients: debounce(function (keyword) {
      this.searchClients(keyword)
    }, 300),
    async searchClients (keyword) {
      if (keyword) {
        if (this.checkKeywordInclude(keyword)) return
        const params = {
          limit: 20,
          offset: 0,
          keyword
        }
        this.loadingClients = true
        const res = await http.fetch(this, api.ticket_clients_list, null, params)
        if (res && res.length > 0) this.clients = res
        this.loadingClients = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.c-ticket {
    &__search {
        margin: 20px 0;
        padding: 20px;
        background-color: snow;
    }
    &__row {
        display: flex;
        align-items: center;
    }

    &__label {
        margin-right: 5px;
    }

    &__item {
        flex: 1;
    }

    &__label--width {
        width: 84px;
    }
}
</style>